/*
 * @Description: 档案分类上下文
 * @Author: Rfan
 * @Date: 2022-05-31 15:25:56
 * @LastEditTime: 2022-06-05 11:54:21
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import {
  ADD_CLASSIFY,
  DELETE_CLASSIFY,
  EDIT_CLASSIFY,
  SET_CLASSIFY_LIST,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_VER_ID
} from '../constants';
import { ArchiveClassifyReducer } from '../reducers/ArchiveClassifyReducer';
import { addMetadata, deleteMetadata } from '@/api/metadata';
import {
  addArchiveClassify,
  deleteArchiveClassify,
  editArchiveClassify,
  fetchArchiveClassifyByPage
} from '@/api/rulesettings/classify';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectVerId: 0,
  // 选中的表格条目
  selectItems: [],

  classifyList: [],

  // dictionarys
  duplicateList: [
    { id: 0, name: '允许', color: 'blue' },
    { id: 1, name: '不允许', color: 'red' }
  ],
  nullList: [
    { id: 0, name: '允许', color: 'blue' },
    { id: 1, name: '不允许', color: 'red' }
  ],
  deleteList: [
    { id: 0, name: '正常', color: 'blue' },
    { id: 1, name: '删除', color: 'red' }
  ],
  typeList: [
    { id: 0, name: '字符型' },
    { id: 1, name: '整型' },
    { id: 2, name: '小数型' },
    { id: 3, name: '日期型' },
    { id: 4, name: '时间型' },
    { id: 5, name: '大对象' }
  ],
  kindList: [
    { id: 0, name: '系统字段', color: 'blue' },
    { id: 1, name: '业务字段', color: 'green' }
  ]
};

const ArchiveClassifyContext = createContext();

const ArchiveClassifyContextProvider = (props) => {
  const [state, dispatch] = useReducer(ArchiveClassifyReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的版本
     * @param {*} id 选中的版本
     */
    setSelectVer(id) {
      dispatch({ type: SET_SELECT_VER_ID, id });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 请求档案分类列表
     * @param {object} params 请求参数
     * @return {*}
     */
    getClassifyList(params) {
      return new Promise((resolve, reject) => {
        fetchArchiveClassifyByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_CLASSIFY_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            dispatch({ type: SET_CLASSIFY_LIST, data: [] });
            reject(err);
          });
      });
    },

    /**
     * @description:增加档案分类
     * @param {*} params 增加档案分类的参数
     * @return {*}
     */
    addClassifyFunc(params) {
      return new Promise((resolve, reject) => {
        addArchiveClassify(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_CLASSIFY, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 编辑档案分类
     * @param {*} params 增加档案分类的参数
     * @return {*}
     */
    editClassifyFunc(params) {
      return new Promise((resolve, reject) => {
        editArchiveClassify(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_CLASSIFY, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 删除档案分类
     * @param {*} id 删除的id
     * @param {*} content 弹窗展示内容
     * @return {*}
     */
    deleteClassifyFunc(id, content = '确认删除该分类？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteArchiveClassify(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_CLASSIFY, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  // watch listQuery来加载列表
  useEffect(() => {
    if (state.listQuery && JSON.stringify(state.listQuery) !== '{}') {
      actions.fetchMatedataFunc(state.listQuery);
    }
  }, [state.listQuery]);

  return (
    <ArchiveClassifyContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </ArchiveClassifyContext.Provider>
  );
};

export const useArchiveClassifyContext = () => {
  return useContext(ArchiveClassifyContext);
};

export { ArchiveClassifyContext, ArchiveClassifyContextProvider };
